﻿using Common.Cache;
using Common.MefHelp.Attributes;
using Common.Self.Computer;
using System.Runtime.InteropServices;
using Common.Tools.Model;
using Common.Tools;
namespace Common.Self
{
    /// <summary>
    /// 自身信息推送
    /// </summary>
    [CustomInjection]
    public class SelfPush
    {
        /// <summary>
        ///  发送自身信息的定时器
        /// </summary>
        private readonly Timer _toSendTimer;
        /// <summary>
        /// 缓存使用
        /// </summary>
        private readonly ICustomCache _customCache;

        /// <summary>
        /// 站点数量
        /// </summary>
        private int _stationNum = 0;
        /// <summary>
        /// 加锁
        /// </summary>
        private static readonly object _lock = new object();
        /// <summary>
        /// key
        /// </summary>
        private readonly string _hostKey = $"{SelfConfig.Instance.Ip.Replace(".", "_")}_{SelfConfig.Instance.Port}";

        /// <summary>
        /// 构造函数
        /// </summary>
        public SelfPush(ICustomCache customCache)
        {
            _toSendTimer = new Timer(SendHandler, null, 1000, Timeout.Infinite);
            _customCache = customCache;
        }
        /// <summary>
        /// 定时发送自身信息
        /// </summary>
        /// <param name="state"></param>
        private async void SendHandler(object? state)
        {
            try
            {
                await UpdateCache();
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }
            finally
            {
                _toSendTimer.Change(60 * 1000, Timeout.Infinite);
            }
        }
        /// <summary>
        /// 获取自身的信息
        /// </summary>
        /// <returns></returns>
        private async Task<SelfDetail> GetSelfDetail()
        {
            var osType= "windows";
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                osType = "windows";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                osType = "linux";
            }
           
            var resource = MefHelp.Mef.GetService<IResource>(osType);
            return new SelfDetail()
            {
                Ip = SelfConfig.Instance.Ip,
                Port = SelfConfig.Instance.Port,
                StationNum = _stationNum,
                Cpu = await resource.GetCpuAsync(),//Convert.ToInt32(DateTime.Now.ToString("ff")),
                AvailableMemeory = await resource.GetAvailableMemeoryAsync(), //Convert.ToInt32(DateTime.Now.ToString("ff")),
                UpdateTime = DateTime.Now,
            };
        }
        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <returns></returns>
        public async Task UpdateCache()
        {
            var self = await GetSelfDetail(); //获取自身信息 
            await _customCache.SetAsync(_hostKey, self, TimeSpan.FromMinutes(5));
        }

        /// <summary>
        /// 处理站点数量
        /// </summary>
        /// <param name="num">传的数量，负数为减去站点数量</param>
        public int HandleStationNum(int num)
        {
            lock (_lock)
            {
                _stationNum += num;
                //LogHelper.Info($"stationNum：{_stationNum}");
                return _stationNum;
            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            LogHelper.Info("自身信息推送启动...");
        }
    }
}
